package com.yoomiito.app.net;

import com.yoomiito.app.BuildConfig;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import cn.droidlover.xdroidmvp.net.XApi;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

public class YmApi {
    //https://mimitao-cdn.aijiamai.com/app/addressNew.json
//    public static final String API_BASE_URL = "http://dev-api1.ymmt.com/";
//    public static final String BaseUrl = "http://r-api1.yoomiito.com/";//测试服
//    public static final String BaseUrl = "https://php-api.yoomiito.com/";//正式服
    public static final String BaseUrl = BuildConfig.BaseUrl;
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private static YmApiServer gankService;
    private static YmApiServer ymApiServer;
    //错误码进行统一处理
    public static YmApiServer getYmService() {
        if (gankService == null) {
            synchronized (YmApi.class) {
                if (gankService == null) {
                    gankService = XApi.getInstance().getRetrofit(BaseUrl, true).create(YmApiServer.class);
                }
            }
        }
        return gankService;
    }

    //错误码没有进行处理
    public static YmApiServer getYmServiceNoErrorCode() {
        if (ymApiServer == null) {
            synchronized (YmApi.class) {
                if (ymApiServer == null) {
                    ymApiServer = XApi.getInstance().getRetrofit(BaseUrl).create(YmApiServer.class);
                }
            }
        }
        return ymApiServer;
    }


    public static YmApiServer downApk() {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(XApi.connectTimeoutMills, TimeUnit.MILLISECONDS)
                .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .addNetworkInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Response originalResponse = chain.proceed(chain.request());//对结果重新处理
                        return originalResponse
                                .newBuilder()
                                .body(new FileResponseBody(originalResponse))//将自定义的ResposeBody设置给它
                                .build();
                    }
                })
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BaseUrl)
                .client(client)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        return retrofit.create(YmApiServer.class);
    }

}
